<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://github.com/mineadmin
-->
<script setup lang="ts">
import type { MaFormExpose } from '@mineadmin/form'
import type { RoleVo } from '~/base/api/role.ts'
import { page } from '~/teacher/api/teacher.ts'
import type { UserVo } from '~/base/api/user.ts'
import { assignTeacher } from '~/classroom/api/classroom.ts'

import useForm from '@/hooks/useForm.ts'

import MaRemoteSelect from '@/components/ma-remote-select/index.vue'
import { ResultCode } from '@/utils/ResultCode.ts'

const { data = null } = defineProps<{
  data?: UserVo | null
}>()

const t = useTrans().globalTrans
const assignTeacherForm = ref<MaFormExpose>()
const userModel = ref<{ id?: number, teacher_ids: string[] }>({
  teacher_ids: [],
})

useForm('assignTeacherForm').then(async (form: MaFormExpose) => {

  if (data?.id) {
    userModel.value.id = data.id
    userModel.value.teacher_ids = data.teachers?.map(t=>t.id) || []
  }

  form.setItems([
    {
      label: () => t('classroom.assign-teacher'),
      prop: 'teacher_ids',
      render: () => MaRemoteSelect,
      renderProps: {
        multiple: true,
        placeholder: t('form.pleaseSelect', { msg: t('classroom.assign-teacher') }),
        api: () => new Promise(resolve => resolve(page({ page_size: 999 }))),
        dataHandle: (response: any) => {
          return response.data.list?.map((item: UserVo) => {
            return { label: `${item.nickname}`, value: item.id }
          })
        },
      },
      itemProps: {
        rules: [{ required: true, message: t('form.requiredSelect', { msg: t('classroom.assign-teacher') }) }],
      },
    },
  ])
  form.setOptions({
    labelWidth: '80px',
  })
})

// 保存用户角色
function saveTeachers(): Promise<any> {
  console.log('1234');
  return new Promise((resolve, reject) =>
    assignTeacher(
      userModel.value.id as number,
      userModel.value.teacher_ids
    ).then((res: any) => {
      res.code === ResultCode.SUCCESS ? resolve(res) : reject(res)
    }).catch((err) => {
      reject(err)
    })
  )
}

defineExpose({
  saveTeachers,
  maForm: assignTeacherForm,
})
</script>

<template>
  <ma-form ref="assignTeacherForm" v-model="userModel" />
</template>

<style scoped lang="scss"></style>
